package com.bytedance.lucky.security;

import com.bytedance.lucky.error.ExceptionEnum;
import com.bytedance.lucky.error.ServiceException;
import com.bytedance.lucky.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zouyaowen
 * @date 2021-02-14 01:07
 */
@Component
public class TokenManager {


    @Autowired
    private JwtUtil jwtUtil;


    public void parseToken(TokenAuthentication tokenAuth) {
        TokenAuthentication.Credentials credentials = (TokenAuthentication.Credentials) tokenAuth.getCredentials();
        HttpServletRequest request = credentials.getRequest();
        String token = this.resolveToken(request);
        Boolean verifyTokenRes = jwtUtil.verifyToken(token);
        if (!verifyTokenRes) {
            throw new ServiceException(ExceptionEnum.AUTHENTICATION_EXPIRED);
        }
    }

    private String resolveToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter(TokenFieldEnum.TOKEN.getField());
        }
        if (StringUtils.isEmpty(token)) {
            throw new ServiceException(ExceptionEnum.AUTHENTICATION_NOT_EXIST);
        }
        return token;
    }
}
